package io.renren.controller;

import io.renren.annotation.Login;
import io.renren.annotation.LoginUser;
import io.renren.common.exception.RRException;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.entity.MemberEntity;
import io.renren.entity.TokenEntity;
import io.renren.form.LoginForm;
import io.renren.service.MemberService;
import io.renren.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import springfox.documentation.annotations.ApiIgnore;

/**
 * 登录接口
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api")
@Api(tags = "登录接口")
public class ApiLoginController extends AbstractController {
	@Autowired
	private MemberService memberService;
	@Autowired
	private TokenService tokenService;

	@PostMapping("login")
	@ApiOperation("登录")
	public R login(@RequestBody LoginForm form) {
		// 表单校验
		ValidatorUtils.validateEntity(form);
		Assert.isTrue(ApiRegisterController.toTencent(form.getTicket(), form.getRandstr()), "验证失败");

		// 用户登录
		Map<String, Object> map = memberService.login(form);

		return R.ok(map);
	}

	@Login
	@PostMapping("resetToken")
	@ApiOperation("重置token")
	public R resetToken(@ApiIgnore @LoginUser MemberEntity member) {
		if (member.getStatus() == ProjectConstant.COMMON_STATUS_DISABLE) {
			tokenService.expireToken(member.getId());
			throw new RRException("账号被禁用", 999);
		}
		TokenEntity tokenEntity = tokenService.createToken(member.getId());// 重置token
		Map<String, Object> map = new HashMap<>(2);
		map.put("token", tokenEntity.getToken());
		map.put("expire", tokenEntity.getExpireTime().getTime());
		return R.ok(map);
	}

	@Login
	@PostMapping("logout")
	@ApiOperation("退出")
	public R logout(@ApiIgnore @RequestAttribute("userId") long userId) {
		tokenService.expireToken(userId);
		return R.ok();
	}

}
